package com.uenpay.oem.ui.reserver;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.socks.library.KLog;
import com.uenpay.im.utilities.ToastUtil;
import com.uenpay.im.utilities.Toasts;
import com.uenpay.im.weight.dialog.LoadDialog;
import com.uenpay.oem.MyApplication;
import com.uenpay.oem.R;
import com.uenpay.oem.common.RxBusEventConstant;
import com.uenpay.oem.ui.main.home.HomeNewFragment;
import com.uenpay.oem.ui.main.my.MyFragment;
import com.uenpay.oem.ui.trans.transfer.TransferActivity;
import com.uenpay.oem.ui.verifyinput.VerifyInputActivity;
import com.uenpay.oem.util.BankCardUtil;
import com.uenpay.oem.util.bankcard.BankCardUtils;
import com.uenpay.oem.widget.dialog.BankCardListDialog;
import com.uenpay.oem.widget.dialog.ReserverodeDialog;
import com.uenpay.oem.widget.listener.AmountEditTextWatcher;
import com.uenpay.service.bean.BankCardInfo;
import com.uenpay.service.bean.TransBankCardList;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.rx.CommonEvent;
import com.uenpay.util.rx.RxBus;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.functions.Action1;


/**
 * Created by PS on 2017/6/18.
 */

public class RechargeActivity extends BaseActivity implements RechargeContract.View {

    public static final String TAG = "RechargeActivity";
    public static final int REQUEST_INPUT_CODE = 201;

    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.rl_bank_layout)
    RelativeLayout rlBankLayout;
    @BindView(R.id.iv_bank_logo)
    ImageView ivBankLogo;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.tv_bank_type)
    TextView tvBankType;
    @BindView(R.id.et_amount)
    EditText etAmount;


    private TransBankCardList<BankCardInfo> mTransBankCardList;

    private RechargeContract.Presenter mRechargePresenter;

    private String mBalance;
    private String phone;

    private BankCardInfo recommendBankCard;
    private String amount;
    private String bankName;
    private String memo;
    private int choosePosition = -1;

    private boolean shouldAddDebitCard = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_recharge;
    }

    @Override
    public void initView(View view) {
        setTitle(R.string.title_charge);
        etAmount.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        etAmount.addTextChangedListener(new AmountEditTextWatcher(etAmount));

        if (getIntent() != null) {
            mBalance = getIntent().getStringExtra("balance");
            if (!TextUtils.isEmpty(mBalance)) {
                tvBalance.setText("我的余额：¥ " + mBalance);
            }
        }

        Observable<CommonEvent> observable = RxBus.$().register(TAG);
        RxBus.$().OnEvent(observable, new Action1<Object>() {
            @Override
            public void call(Object obj) {
                CommonEvent event = (CommonEvent) obj;
                if (event.getWhat() == RxBusEventConstant.EVENT_RETRY_SEND_CODE) {
                    amount = etAmount.getText().toString().trim();
                    memo = recommendBankCard.getUserBankId() + "";
                    phone = recommendBankCard.getPhone();
                    mRechargePresenter.sendSmsCode(amount, memo, false);
                }
            }
        });

    }

    @Override
    public void showLoading() {
        LoadDialog.show(this);
    }

    @Override
    public void dismissLoading() {
        LoadDialog.dismiss(this);
    }

    @Override
    public void setPresenter(Object presenter) {
        mRechargePresenter = new RechargePresenter(this);
    }

    @Override
    public void showToast(String msg) {
        Toasts.shortToast(this, msg);
    }

    @Override
    public void setTransBankCardList(TransBankCardList<BankCardInfo> list) {
        mTransBankCardList = list;
        String isOpenCredit = mTransBankCardList.getIsOpenCredit();
        //不允许使用信用卡
        if (isOpenCredit.equals("1")) {
            int firstDebitCardPosition = -1; //第一张储蓄卡位置
            for (int i = 0; i < mTransBankCardList.getBankCardList().size(); i++) {
                if (mTransBankCardList.getBankCardList().get(i).getCardType().equals("1")) {
                    firstDebitCardPosition = i;
                    break;
                }
            }
            //没有储蓄卡
            if (firstDebitCardPosition == -1) {
                Toasts.shortToast(this, "无法使用信用卡充值，请先添加储蓄卡");
                shouldAddDebitCard = true;
                //无储蓄卡时默认银行卡为第一张信用卡
                recommendBankCard = mTransBankCardList.getBankCardList().get(0);
            } else {
                choosePosition = firstDebitCardPosition;
                recommendBankCard = mTransBankCardList.getBankCardList().get(firstDebitCardPosition);
            }
        } else {
            choosePosition = 0;
            recommendBankCard = mTransBankCardList.getBankCardList().get(0);
        }
        initBankView();
    }

    void initBankView() {
        ivBankLogo.setVisibility(View.VISIBLE);
        ivBankLogo.setImageResource(BankCardUtil.getLogoByBankName(recommendBankCard.getBankName()));
        String cardNum = recommendBankCard.getCardNo();
        String cardEndNum = BankCardUtils.getSubBankNum(cardNum, BankCardUtils.REMAIN);
        bankName = recommendBankCard.getBankName() + "   (" + cardEndNum + ")";
        tvBankName.setText(bankName);
        tvBankType.setText(BankCardUtil.getBankCardType(recommendBankCard.getCardType()));
    }

	@OnClick(R.id.btn_next)
	public void next() {
        if (shouldAddDebitCard) {
            ToastUtil.showToast(this, "需要添加储蓄卡");
            return;
        }
        amount = etAmount.getText().toString().trim();
        memo = recommendBankCard.getUserBankId() + "";
        phone = recommendBankCard.getPhone();
        mRechargePresenter.sendSmsCode(amount, memo, true);
    }

    @Override
    public void showInputSmsDialog() {
        Intent intent = new Intent(RechargeActivity.this, VerifyInputActivity.class);
        intent.putExtra("title", "请输入验证码");
        intent.putExtra("subtitle", "验证码已发送至 " + recommendBankCard.getPhone());
        intent.putExtra("amount", amount);
        intent.putExtra("show_send_retry", true);
        intent.putExtra("show_pwd", true);
        intent.putExtra("input_length", 6);
        startActivityForResult(intent, REQUEST_INPUT_CODE);
    }

    @Override
    public void goSuccess() {

        Intent intent = new Intent(RechargeActivity.this, RechargesucceedActivity.class);
        intent.putExtra("amount", amount);
        intent.putExtra("bankName", bankName);
        startActivity(intent);
        //发通知
        RxBus.$().post(MyFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_RECHARGE_SUCCESS));
        RxBus.$().post(HomeNewFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_RECHARGE_SUCCESS));
        finish();
    }

    @Override
    public void setRecommendBank(int position) {
        recommendBankCard = mTransBankCardList.getBankCardList().get(position);

        initBankView();
    }

    @OnClick(R.id.rl_bank_layout)
    public void chooseBankCard() {

        if (mTransBankCardList != null && mTransBankCardList.getBankCardList().size() > 0) {
            final BankCardListDialog dialog = new BankCardListDialog(RechargeActivity.this, mTransBankCardList, choosePosition);
            dialog.setonaddlistener(new BankCardListDialog.onaddclickListenner() {
                @Override
                public void onaddclick() {
                    //添加银行卡
                    Intent intent = new Intent(RechargeActivity.this, AddnewcardActivity.class);
                    startActivity(intent);
                    dialog.dismiss();
                }
            });
            dialog.setOnChooseBankListener(new BankCardListDialog.OnChooseBankListener() {
                @Override
                public void choose(int position) {
                    // showToast(mTransBankCardList.getBankCardList().get(position).toString());
                    mRechargePresenter.chooseBank(position);
                    choosePosition = position;
                }
            });
            //点击关闭
            dialog.setoncloseListener(new BankCardListDialog.oncloseclickListener() {
                @Override
                public void oncloseClick() {
                    dialog.dismiss();
                }
            });
            dialog.show();
        } else {
            Toasts.shortToast(this, "未获取到银行卡信息");
        }
    }

    private void initData() {
        setPresenter(null);
        mRechargePresenter.getTransBankCardList();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == REQUEST_INPUT_CODE) {
            String pwd = data.getStringExtra("pwd");
            KLog.d(TAG, "[onActivityResult] pwd=" + pwd);
            mRechargePresenter.recharge(pwd);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.$().unregister(TAG);
    }
}